<template>
    <div class="PersonalSetting">
      <el-row>
        <el-col :offset="1" :span="22">
          <div class="grid-content bg-purple-dark">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <el-button class="button" type="text" @click="handleBack"><i class="el-icon-arrow-left" />返回</el-button>
                  <span>数据集</span>
                  <div></div>
                </div>
              </template>
              <el-tabs tab-position="tabPosition">
                <el-tab-pane label="基本设置">
                  <div class="set-info">
                    <div class="avatar">
                      <div class="preview">
                        <span>{{this.form.herbName}}</span>
                        <img v-if="showImg()" :src="showImg()" />
                      </div>
                    </div>
                    <div class="form-info">
                        <el-descriptions  class="margin-top" title="详细信息" :column="3" colon>
                            <el-descriptions-item label="拉丁学名"><div class="info_container"> {{ form.latinName  }} </div></el-descriptions-item>
                            <el-descriptions-item label="别名"><div class="info_container"> {{ form.alias }} </div></el-descriptions-item>
                            <el-descriptions-item label="功效分类"><div class="info_container"> {{ typeName }} </div></el-descriptions-item>
                            <el-descriptions-item label="药用部分"><div class="info_container"> {{ form.medicinalPart }} </div></el-descriptions-item>
                            <el-descriptions-item label="性味"><div class="info_container"> {{ form.natureFlavor }} </div></el-descriptions-item>
                            <el-descriptions-item label="归经"><div class="info_container"> {{ form.channelTropism }} </div></el-descriptions-item>
                            <el-descriptions-item label="产地分布"><div class="info_container " style="height: 40px;"> {{ form.originDistribution }} </div></el-descriptions-item>
                            <el-descriptions-item label="采收加工"><div class="info_container"> {{ form.harvestingProcessing }} </div></el-descriptions-item>
                            <el-descriptions-item label="功效与作用"><div class="info_container"> {{ form.efficacyEffect }} </div></el-descriptions-item>
                            <el-descriptions-item label="植物形态"><div class="info_container big"> {{ form.plantMorphology }} </div></el-descriptions-item>
                            <el-descriptions-item label="临床应用"><div class="info_container big"> {{ form.clinicalApplication }} </div></el-descriptions-item>
                            <el-descriptions-item label="药理研究"><div class="info_container big"> {{ form.pharmacologicalResearch }} </div></el-descriptions-item>
                            <el-descriptions-item label="药材性状"><div class="info_container big"> {{ form.drugProperties }} </div></el-descriptions-item>
                            <el-descriptions-item label="化学成分"><div class="info_container big"> {{ form.chemicalComponent }} </div></el-descriptions-item>
                            <el-descriptions-item label="使用禁忌"><div class="info_container"> {{ form.usageTaboo }} </div></el-descriptions-item>
                            <el-descriptions-item label="配伍药方"><div class="info_container"> {{ form.compatiblePrescription }} </div></el-descriptions-item>
                        </el-descriptions>
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="训练集" ref="train_tab">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <div class="set-title" style="height: 450px;">
                                    <span>已有训练集</span>
                                    <div class="scroll-container">
                                        <div class="demo-image__lazy"  >
                                            <el-image @click="delete_dataset($event, 1)" v-for="train_dataset in this.stay_show.train_dataset" :id="train_dataset.id" :key="train_dataset.id" :src="convertToImage(train_dataset.img)"></el-image>
                                        </div>
                                    </div>
                                </div>
                                <div class="pager">
                                    <el-pagination
                                        layout="prev, pager, next"
                                        :total="train_total"
                                        style="margin-left: 80px;"
                                        @current-change="train_handlePage">
                                    </el-pagination>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <div class="upload_container">
                                    <el-upload
                                    class="upload-demo"
                                    drag
                                    :show-file-list="true"
                                    :http-request="uploadFile"
                                    :auto-upload="false"
                                    ref="upload_train"
                                    action="#"
                                    multiple>
                                        <i class="el-icon-upload"></i>
                                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                                    </el-upload>
                                </div>
                                <div class="img_upload_button">
                                  <el-button type="primary" @click="submit_train()">上传训练图片</el-button>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="测试集">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <div class="set-title" style="height: 450px;">
                                    <span>已有测试集</span>
                                    <div class="scroll-container">
                                        <div class="demo-image__lazy"  >
                                            <el-image @click="delete_dataset($event, 0)" v-for="test_dataset in this.stay_show.test_dataset" :id="test_dataset.id" :key="test_dataset.id" :src="convertToImage(test_dataset.img)"></el-image>
                                        </div>
                                    </div>
                                </div>
                                <div class="pager">
                                    <el-pagination
                                        layout="prev, pager, next"
                                        :total="test_total"
                                        style="margin-left: 80px;"
                                        @current-change="test_handlePage">
                                    </el-pagination>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                              <div class="upload_container">
                                    <el-upload
                                    class="upload-demo"
                                    drag
                                    :show-file-list="true"
                                    :http-request="uploadFile"
                                    :auto-upload="false"
                                    ref="upload_test"
                                    action="#"
                                    multiple>
                                        <i class="el-icon-upload"></i>
                                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                                    </el-upload>
                                </div>
                                <div class="img_upload_button">
                                  <el-button type="primary" @click="submit_test()">上传测试图片</el-button>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                </el-tab-pane>
              </el-tabs>
            </el-card>
        </div>
        </el-col>
      </el-row>
    </div>
  </template>

<script>
export default {
    data(){
        return{
          herbTypeList:[],
          train_total:0,
          train_pageData:{
              page:1,
              size:10
          },
          test_total:0,
          test_pageData:{
              page:1,
              size:10
          },
          state:1,// 1 上传训练集 0 上传测试集
          stay_upload:{
            train_dataset:[],
            test_dataset:[]
          },
          form:{ 
            id:"",
            herbName: "",
            latinName: "",
            herbTypeId: "",
            medicinalPart: "",
            alias: "",
            plantMorphology: "",
            originDistribution: "",
            harvestingProcessing: "",
            drugProperties: "",
            natureFlavor: "",
            channelTropism: "",
            efficacyEffect: "",
            clinicalApplication: "",
            pharmacologicalResearch: "",
            chemicalComponent: "",
            usageTaboo: "",
            compatiblePrescription: "",
          },
          stay_show:{
            train_dataset:[],
            test_dataset:[]
          },
        }
     },
                        
    methods:{
        getHerbalTypeList(){
            this.$axios.get('/selectByHerbType')
            .then(({data}) => {// 请求成功，返回
                console.log(data);
                if(data.code===200){
                    this.herbTypeList=data.list
                }else{
                    this.$message.error(data.data.message)
                }
            })
            .catch((err) => {// 请求失败
                console.log(err);
            });
        },
        delete_dataset(val,state){
          let url=""
          if(state==1){
            url='/deleteTrainDataset'
          }else{
            url='/deleteTestDataset'
          }
          const id = val.target.getAttribute ('id') 
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    this.$axios.delete(url,{
                    data: {
                        id: id
                    }}).then(({data})=>{
                    if(data.code==200){
                      this.$message({
                        type: 'success',
                        message: data.data.message
                      });
                      if(state==1){
                        this.getDataset("/getTrainDataset",{params:{...this.train_pageData,id:this.form.id}},1)
                      }else{
                        this.getDataset("/getTestDataset",{params:{...this.test_pageData,id:this.form.id}},0)
                      }
                    }else{
                      this.$message({
                        type: 'error',
                        message: data.data.message
                      });
                    }
                    
                })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
        },
        train_handlePage(val){
          this.train_pageData.page = val
          this.getDataset("/getTrainDataset",{params:{...this.train_pageData,id:this.form.id}},1)
        },
        test_handlePage(val){
          this.test_pageData.page = val
          this.getDataset("/getTestDataset",{params:{...this.test_pageData,id:this.form.id}},0)
        },
        getDataset(url,obj,state){
          if(state==1){
            this.stay_show.train_dataset=[]
          }else{
            this.stay_show.test_dataset=[]
          }
          this.$axios.get(url,obj).then(({data}) => {
              for(let index in data.list){
                if(state==1){
                  this.stay_show.train_dataset.push(data.list[index]);
                }else{
                  this.stay_show.test_dataset.push(data.list[index]);
                }
              }
              if(state==1){
                this.train_total=data.data.pageData.count
              }else{
                this.test_total=data.data.pageData.count
              }
          })
        },
        uploadFile(param){
          console.log(param)
          if(this.state==1){
            this.stay_upload.train_dataset.push(param.file)
          }else{
            this.stay_upload.test_dataset.push(param.file)
          }
        },
        submit(url,file){
          const formDatas = new FormData();
          formDatas.append("file",file)
          formDatas.append("id",this.form.id)
          this.$axios.post(url,formDatas, {headers: {'Content-Type': 'multipart/form-data'}}).then(({data}) => {// 请求成功，返回
              console.log(data);
              if(data.code==200){
                  this.$message({
                      type: 'success',
                      message: data.data.message
                  });
              }else {
                      this.$message({
                      type: 'error',
                      message: data.data.message
                  });
              }
          }).catch((err) => {// 请求失败
              console.log(err);
          });
        },
        submit_train(){
          this.state=1
          this.$refs.upload_train.submit()
          for(let index in this.stay_upload.train_dataset){
            this.submit("/addTrainDataset",this.stay_upload.train_dataset[index])
          }
          this.$refs.upload_train.clearFiles()
          this.stay_upload.train_dataset=[]
          setTimeout(() => {
            this.getDataset("/getTrainDataset",{params:{...this.train_pageData,id:this.form.id}},1)
          }, 500);
        },
        submit_test(){
          this.state=0
          this.$refs.upload_test.submit()
          for(let index in this.stay_upload.test_dataset){
            this.submit("/addTestDataset",this.stay_upload.test_dataset[index])
          }
          this.$refs.upload_test.clearFiles()
          this.stay_upload.test_dataset=[]
          setTimeout(() => {
            this.getDataset("/getTestDataset",{params:{...this.test_pageData,id:this.form.id}},0)
          }, 500);
        },
        convertToImage(binaryString) {
          const byteCharacters = atob(binaryString); // 将base64编码的二进制字符串解码为原始字节流
          const byteArrays = [];
            for (let offset = 0; offset < byteCharacters.length; offset += 512) {
                const slice = byteCharacters.slice(offset, offset + 512);
                const byteNumbers = new Array(slice.length);
                for (let i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                  }
              const byteArray = new Uint8Array(byteNumbers);
              byteArrays.push(byteArray);
            }
          const blob = new Blob(byteArrays, { type: 'image/jpeg' }); // 根据实际情况设置MIME类型
          return URL.createObjectURL(blob); // 生成URL
        },
        showImg(){
          return this.convertToImage(this.form.img)
        },
        getHerbId(){
          this.form.id=this.$route.query.id
          this.$axios.get('/getHerbById',{params:{"id":this.form.id}}).then(({data}) =>{
            this.form=data.data.herb
          })
        },
        handleBack(){
            this.$router.push("/chineseHerbalMedicine")
        },
        beforeAvatarUpload(){
            console.log("上传图片前")
        },
        handleAvatarSuccess(){
            console.log("上传图片成功时")
        }
     },
    mounted(){
      this.getHerbalTypeList()
      this.getHerbId()
      this.getDataset("/getTrainDataset",{params:{...this.train_pageData,id:this.form.id}},1)
      this.getDataset("/getTestDataset",{params:{...this.test_pageData,id:this.form.id}},0)
    },
    computed:{
      typeName(){
        let name=""
        for(let ind in this.herbTypeList){
          if(this.herbTypeList[ind].id==this.form.herbTypeId){
            name=this.herbTypeList[ind].typeName
          }
        }
        return name
      }
    }
}
</script>

<style lang="less" scoped>
.img_upload_button{
    margin-top: 30px;
    .el-button{
      margin-right: 110px;
    }
}
.info_container{
  overflow-y:auto;
  font-size: 12px;
}
.big{
  height: 60px;
}
.demo-image__lazy {
    height: 400px;
    width: 500px;
    overflow-y: auto;
    margin-top: 30px;
    margin-left: 30px;
    .el-image {
        display: block;
        min-height: 300px;
        margin-bottom: 10px;
    }
}

.PersonalSetting{
    margin-top:20px;
    .demo-ruleForm{
        text-align :left;
    }
    .set-title{
      text-align :left;
    }
    .secure-item{
      width:100%;
      padding:20px;
      border-bottom:1px solid #f0f0f0;
      display :flex;
      flex-direction:row;
      justify-content :space-between;
      align-items :center;
      .secure-info{
         display :flex;
      flex-direction:column;
      justify-content :flex-start;
      align-items :flex-start;
        .secure-key{
          margin-bottom: 4px;
          color: rgba(0,0,0,.85);
          font-size: 14px;
          line-height: 1.6;
        }
        .secure-value{
          color: rgba(0,0,0,.45);
          font-size: 14px;
          line-height: 1.6;
        }
      }
      .opera-btn{
        color:#1890ff;
        cursor:pointer;
        margin-right: 50px;
      }
    }
    .set-info{
      display :flex;
      flex-direction :row;
      justify-content :space-around;
      align-items :flex-start;
      padding: 20px;
      .form-info{

      }
      .avatar{
        display :flex;
        flex-direction:row;
        justify-content:flex-start;
        align-items :flex-end;
        .preview{
           display :flex;
          flex-direction:column;
          justify-content:flex-start;
          align-items :flex-start;
          margin-right:50px;
          margin-left:50px;
         img{
            width:174px;
          height:174px;
          border-radius:50%;
         }
        }

          .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
          }
          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
          }
          .avatar {
            width: 178px;
            height: 178px;
            display: block;
          }
      }
    }
    .info{
        text-align: left;
      padding-left: 20px;
      margin-bottom: 20px;
      font-size: 12px;
    }
     .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .box-card {
    width:100%;
  }
}
</style>